#include "bsp_usart1.h"





Queue queue_usart = {0};


void Usart1_Init(void)
{
	GPIO_InitTypeDef  GPIO_InitStructure;
	USART_InitTypeDef  USART_InitStructure;
	NVIC_InitTypeDef   NVIC_InitStructure;
	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);

	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
	GPIO_InitStructure.GPIO_Pin  = GPIO_Pin_9 ;  //TX
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
	GPIO_InitStructure.GPIO_Pin  = GPIO_Pin_10 ;  //RX
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	
	USART_InitStructure.USART_BaudRate = USART1_BAUD;  
	USART_InitStructure.USART_WordLength = USART_WordLength_8b;
	USART_InitStructure.USART_StopBits = USART_StopBits_1;
	USART_InitStructure.USART_Parity =  USART_Parity_No;
	USART_InitStructure.USART_Mode = USART_Mode_Rx |USART_Mode_Tx;
	USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	USART_Init(USART1, &USART_InitStructure);
	

	NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;  
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStructure);
	USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);

	USART_Cmd(USART1, ENABLE);
	
	USART_ClearFlag(USART1, USART_FLAG_TC  );

	Queue_Init(&queue_usart);

}


static void Usart1_SendByte(uint8_t ch)
{
	
	USART_SendData(USART1, (uint8_t)ch);
	
	while(USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);
}


void Usart1_SendString(uint8_t *str) 
{
	uint32_t pos = 0;
	while(*(str+pos)!='\0')
	{
		Usart1_SendByte(*(str+pos));
		pos ++;
		
	}
}


int fputc(int ch, FILE *f)
{
	
	USART_SendData(USART1, (uint8_t)ch);
	
	while(USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);
	
	return (ch);

}

void USART1_IRQHandler(void)
{
	char RecCh;
	if( USART_GetFlagStatus(USART1, USART_FLAG_RXNE) != RESET )
	{	
		RecCh =(char)USART_ReceiveData(USART1);
        Queue_push(&queue_usart, RecCh);
		USART_ClearFlag(USART1, USART_FLAG_RXNE);
	}
	if( USART_GetFlagStatus(USART1, USART_FLAG_ORE) == SET )
	{
		USART_ClearFlag(USART1, USART_FLAG_ORE);
	}
}




